﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using Table = FCNS.Data.Table;
using System.Collections.ObjectModel;
using DoubleH.Utility;
using System.Diagnostics;

namespace POS
{
    /// <summary>
    /// WindowSelectPayMode.xaml 的交互逻辑
    /// </summary>
    public partial class WindowSelectPayMode : Window
    {
        public WindowSelectPayMode()
        {
            InitializeComponent();

            InitVar();
            InitEvent();
        }
        /// <summary>
        /// 是否已经选择了支付
        /// </summary>
        public bool IsPayed { get; set; }

        private void InitVar()
        {
            if (App.Order.CorSId == -1 || App.Vip == null)
                buttonVip.IsEnabled = false;

            listBoxCoupons.DisplayMemberPath = "OrderNO";
            IsPayed = false;
            textBoxCoupons.Focus();
        }

        private void InitEvent()
        {
            buttonCash.Click += (ss, ee) => PayByCash();
            buttonVip.Click += (ss, ee) => PayByVip();
            buttonCard.Click += (ss, ee) => PayByCard();
            buttonCoupons.Click += (ss, ee) => AddCoupons();
            listBoxCoupons.MouseDoubleClick += (ss, ee) => RemoveCoupons();
        }

        public void Init()
        {
                //buttonCoupons.IsEnabled =App.OnLine;
        }

        private void PayByCash()
        {
            CalcCouponsMoney();
            PayNow();
        }

        private void PayByVip()
        {
            Debug.Assert(App.Vip != null);
            CalcCouponsMoney();
            CalcVipMoney();
            PayNow();
        }

        private void PayByCard()
        {
            CalcCouponsMoney();
            if (MessageWindow.Show("", "'确定'刷卡成功,'取消'重选支付方式", MessageBoxButton.OKCancel) == MessageBoxResult.No)
            {
                App.Order.CalcMoney();
                this.Close();
            }
            else
                PayNow();
        }

        private void AddCoupons()
        {
            textBoxCoupons.Focus();

            if (string.IsNullOrEmpty(textBoxCoupons.Text))
                return;

            if (!Table.SysConfig.SysConfigParams.MoreCoupons && listBoxCoupons.HasItems)
                return;

            if (listBoxCoupons.Items.Contains(textBoxCoupons.Text))
                return;

            Table.CouponsS ps=Table.CouponsS.IsExist(textBoxCoupons.Text);
            if (ps != null)
            {
                //有些优惠券是指定商品的，如果客户买的商品不再其列表，就不使用了。
                if (!string.IsNullOrEmpty(ps.ProductSIdList))
                {
                    string[] str = ps.ProductSIdList.Split(',');
                    var vr = App.Order.ProductSList.Where(f => str.Contains(f.Id.ToString()));
                    if (vr == null || vr.Count() == 0)
                    {
                        MessageWindow.Show("你购买的商品不适用于此优惠券");
                        return;
                    }
                }

                listBoxCoupons.Items.Add(ps);
            }
            else
                DoubleH.Utility.MessageWindow.Show(textBoxCoupons.Text + " 已失效或不存在");

            textBoxCoupons.Clear();
        }

        private void RemoveCoupons()
        {
            textBoxCoupons.Focus();

            if (listBoxCoupons.SelectedItem == null)
                return;

            listBoxCoupons.Items.Remove(listBoxCoupons.SelectedItem);
        }
        /// <summary>
        /// 冲减优惠券金额
        /// </summary>
        /// <returns></returns>
        private void CalcCouponsMoney()
        {
            if (!listBoxCoupons.HasItems)
                return ;

            if (App.Order.Money == 0)
                return;

            Dictionary<string, double> allProduct = new Dictionary<string, double>();
            foreach (Table.ProductS ps in App.Order.ProductSList)
            {
                if (allProduct.Keys.Contains(ps.Id.ToString()))
                    allProduct.Add(ps.Id.ToString(), ps._TempSum);
                else
                    allProduct[ps.Id.ToString()] = allProduct[ps.Id.ToString()] + ps._TempSum;
            }

            double dAll = 0;//用来存储没有指定商品的优惠券的合计金额
            foreach (object obj in listBoxCoupons.Items)
            {
                Table.CouponsS ps = obj as Table.CouponsS;
                if (string.IsNullOrEmpty(ps.ProductSIdList))
                    dAll += ps.Money;
                else
                {
                    foreach (string str in ps.ProductSIdList.Split(','))
                    {
                        if (ps.Money == 0)
                            break;//如果此优惠券已经没钱了,就跳出.

                        if (!allProduct.Keys.Contains(str))
                            continue;

                        double dValue = allProduct[str];
                        if (dValue == 0)
                            continue;

                        Debug.Assert(dValue >= 0);
                        if (dValue < ps.Money)
                        {
                            dValue = 0;
                            ps.Money -= dValue;
                        }
                        else
                        {
                            allProduct[str] = dValue - ps.Money;
                            ps.Money = 0;
                        }
                    }
                }
            }

            double dd=allProduct.Sum(f => f.Value);
            if (dd > dAll)
               App.Order.Money= dd - dAll;
            else
                App.Order.Money = 0;
        }
        /// <summary>
        /// 冲减VIP积分金额
        /// </summary>
        private void CalcVipMoney()
        {
            if (App.Order.Money == 0)
                return;

            double integral=0;
            if (App.Vip.VipRemainIntegral > App.Order.Money)
            {
                App.Vip.VipRemainIntegral -= App.Order.Money;
                integral = App.Order.Money;
                App.Order.Money = 0;
            }
            else
            {
                App.Order.Money -= App.Vip.VipRemainIntegral;
                integral = App.Vip.VipRemainIntegral;
                App.Vip.VipRemainIntegral = 0;
            }
            App.Vip.UpdateRemainIntegral();

            Table.VipIO io = new Table.VipIO();
            io.CorSId = App.Vip.Id;
            io.OrderDateTime = App.Order.OrderDateTime;
            io.OrderNO = App.Order.OrderNO;
            io.VipIntegral = -integral;
            io.Enable = Table.VipIO.EnumEnable.入账;
            Debug.Assert(io.Insert() == Table.DataTableS.EnumDatabaseStatus.操作成功);
        }

        private void PayNow()
        {
            App.ShowLed(App.Order.Money.ToString(),string.Empty);
            IsPayed = true;
            this.Close();
        }
    }
}
